package com.ruoyi.common.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author TsingYu
 * @version 1.0
 * @date 2025/9/17 10:05
 */
public class MapKeyUnderlineToCamelUtil {

    /**
     * 将单个Map的key从下划线转为驼峰
     */
    public static Map<String, Object> underlineToCamel(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return new HashMap<>();
        }

        Map<String, Object> resultMap = new HashMap<>(map.size());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            // 转换key为驼峰命名
            String camelKey = underlineToCamel(key);
            resultMap.put(camelKey, value);
        }
        return resultMap;
    }

    /**
     * 将List<Map>中所有Map的key从下划线转为驼峰
     */
    public static List<Map<String, Object>> underlineToCamel(List<Map<String, Object>> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }

        return list.stream()
                .map(MapKeyUnderlineToCamelUtil::underlineToCamel)
                .collect(Collectors.toList());
    }

    /**
     * 下划线字符串转驼峰字符串
     */
    private static String underlineToCamel(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        // 如果没有下划线，直接返回
        if (!str.contains("_")) {
            return str;
        }

        StringBuilder sb = new StringBuilder();
        boolean nextUpperCase = false;

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);

            if (c == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    sb.append(Character.toUpperCase(c));
                    nextUpperCase = false;
                } else {
                    sb.append(c);
                }
            }
        }

        return sb.toString();
    }
}
